<template>
  <view class="container">
    <!-- 商品图片 -->
    <image :src="service.internalServiceImage" class="service-image" mode="widthFix" />

    <!-- 商品信息 -->
    <view class="product-info">
      <text class="product-name">{{ service.serviceName }}</text>
      <text class="product-price">¥{{ service.price }}</text>
      <text class="product-description">{{ service.description }}</text>
    </view>

    <!-- 数量选择 -->
    <!-- <view class="quantity-selector">
      <text class="label">购买数量</text>
      <view class="quantity-controls">
        <button class="quantity-btn" @click="decreaseQuantity" :disabled="quantity <= 1">-</button>
        <input type="number" v-model="quantity" class="quantity-input" />
        <button class="quantity-btn" @click="increaseQuantity">+</button>
      </view>
    </view> -->

    <!-- 确认区域 -->
    <!-- <view class="confirm-section">
      <view class="total-price">
        <text>总价：</text>
        <text class="price">¥{{ (service.price * quantity).toFixed(2) }}</text>
      </view>
      <button class="confirm-button" @click="handleBuy">立即购买</button>
    </view> -->

    <!-- 悬浮购物车按钮 -->
    <!-- <view class="cart-fab" @click="showCart = true">
      <image src="../../../../../static/icons/购物车.png" class="cart-icon" />
      <view class="cart-count" v-if="cart.length">{{ cart.reduce((sum, item) => sum + item.quantity, 0) }}</view>
    </view> -->

    <!-- 购物车弹窗 -->
    <view v-if="showCart" class="cart-popup">
      <view class="cart-title">购物车</view>
      <view v-if="cart.length === 0" class="cart-empty">购物车为空</view>
      <view v-for="item in cart" :key="item.id" class="cart-item">
        <image :src="item.internalServiceImage || item.productImage" class="cart-item-img" />
        <text class="cart-item-name">{{ item.serviceName || item.productName }}</text>
        <view class="cart-item-controls">
          <button @click="removeFromCart(item)">-</button>
          <text>{{ item.quantity }}</text>
          <button @click="addToCart(item)">+</button>
        </view>
      </view>
      <view class="cart-footer">
        <button class="checkout-btn" @click="showCart = false">关闭</button>
      </view>
    </view>

    <!-- 购物车条（底部） -->
    <view class="cart-bar">
      <image src="../../../../../static/icons/购物车.png" class="cart-bar-icon" @click="showCart = true" />
      <view class="cart-bar-amount">
        合计：<text class="cart-bar-price">¥{{ cart.reduce((sum, item) => sum + item.price * item.quantity, 0).toFixed(2) }}</text>
      </view>
      <!-- <button class="cart-bar-pay-btn" :disabled="cart.length === 0" @click="goToPay">去支付</button> -->
    </view>

    <!-- 公告栏 -->
    <!-- <view v-if="noticeContent" class="notice-bar">
      <text class="notice-content">{{ noticeContent }}</text>
    </view> -->
    <view v-if="noticeContent" class="notice-bar">
      <text>{{ noticeContent }}</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getOpenId } from '@/api/wxlogin/wxlogin'
import { getNoticeList } from '@/api/content/banner'

const service = ref({})
const quantity = ref(1)
const cart = ref([]) // 新增
const showCart = ref(false) // 控制购物车弹窗的显示与隐藏
const showAuthModal = ref(false); // 顶部已定义则不用重复
const noticeContent = ref('')

onLoad((options) => {
  if (options.service) {
    service.value = JSON.parse(decodeURIComponent(options.service))
  }
  if (options.cart) {
    cart.value = JSON.parse(decodeURIComponent(options.cart))
  }
})

// 购物车相关方法
const getCartQuantity = (productId) => {
  const item = cart.value.find(i => i.id === productId)
  return item ? item.quantity : 0
}
const addToCart = (product) => {
  const idx = cart.value.findIndex(i => i.id === product.id)
  if (idx > -1) {
    cart.value[idx].quantity += 1
  } else {
    cart.value.push({ ...product, quantity: 1 })
  }
}
const removeFromCart = (product) => {
  const idx = cart.value.findIndex(i => i.id === product.id)
  if (idx > -1) {
    if (cart.value[idx].quantity > 1) {
      cart.value[idx].quantity -= 1
    } else {
      cart.value.splice(idx, 1)
    }
  }
}

const increaseQuantity = () => {
  quantity.value++
}

const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}

const handleBuy = () => {
  const orderInfo = {
    ...service.value,
    quantity: quantity.value,
    totalPrice: (service.value.price * quantity.value).toFixed(2)
  }

  uni.login({
    success: async (res) => {
      if (res.code) {
        try {
          const openIdRes = await getOpenId(res.code)
          if (openIdRes.data && openIdRes.data.openid) {
            orderInfo.openid = openIdRes.data.openid
            // 修改为正确的支付页面路径
            uni.navigateTo({
              url: `/pages/customer-platform/wxpay/payment/index?service=${encodeURIComponent(JSON.stringify(orderInfo))}`
            })
          } else {
            uni.showToast({
              title: '获取用户信息失败',
              icon: 'none'
            })
          }
        } catch (err) {
          console.error('获取openid失败:', err)
          uni.showToast({
            title: '获取用户信息失败',
            icon: 'none'
          })
        }
      }
    },
    fail: (err) => {
      console.error('wx.login 调用失败', err)
      uni.showToast({
        title: '登录失败',
        icon: 'none'
      })
    }
  })
}

const goToPay = () => {
  if (!uni.getStorageSync('isLoggedIn')) {
    showAuthModal.value = true;
    return;
  }
  if (cart.value.length === 0) {
    uni.showToast({ title: '购物车为空', icon: 'none' });
    return;
  }
  uni.navigateTo({
    url: `/pages/customer-platform/wxpay/payment/index?cart=${encodeURIComponent(JSON.stringify(cart.value))}`
  });
};

onMounted(async () => {
  const res = await getNoticeList()
  if (res.code === 200 && Array.isArray(res.data)) {
    // 例如只取type2
    const type2Notice = res.data.find(item => item.noticeId === 3)
    if (type2Notice) {
      noticeContent.value = type2Notice.notice
    }
  }
})
</script>

<style lang="scss" scoped>
.container {
  padding: 32rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx; // 为底部按钮预留空间
}

.service-image {
  width: 100%;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
}

.product-info {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;

  .product-name {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 16rpx;
    display: block;
  }

  .product-price {
    font-size: 40rpx;
    color: #ff0000;
    font-weight: bold;
    margin-bottom: 16rpx;
    display: block;
  }

  .product-description {
    font-size: 28rpx;
    color: #666;
    line-height: 1.5;
  }
}

.quantity-selector {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .label {
    font-size: 28rpx;
    color: #333;
  }

  .quantity-controls {
    display: flex;
    align-items: center;
    
    .quantity-btn {
      width: 60rpx;
      height: 60rpx;
      font-size: 32rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f5f5f5;
      border: none;
      border-radius: 8rpx;

      &:disabled {
        opacity: 0.5;
      }
    }

    .quantity-input {
      width: 80rpx;
      height: 60rpx;
      text-align: center;
      margin: 0 16rpx;
      background-color: #f5f5f5;
      border: none;
      border-radius: 8rpx;
    }
  }
}

.confirm-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1);

  .total-price {
    font-size: 28rpx;
    
    .price {
      color: #ff0000;
      font-size: 36rpx;
      font-weight: bold;
    }
  }

  .confirm-button {
    background-color: #ffcc00;
    color: #333;
    font-size: 32rpx;
    padding: 20rpx 60rpx;
    border-radius: 40rpx;
    border: none;

    &:active {
      opacity: 0.8;
    }
  }
}

.cart-fab {
  position: fixed;
  right: 40rpx;
  bottom: 120rpx;
  width: 100rpx;
  height: 100rpx;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;

  .cart-icon {
    width: 60rpx;
    height: 60rpx;
  }

  .cart-count {
    position: absolute;
    top: 10rpx;
    right: 10rpx;
    background: #ff0000;
    color: #fff;
    border-radius: 50%;
    padding: 4rpx 10rpx;
    font-size: 24rpx;
    min-width: 32rpx;
    text-align: center;
  }
}

.cart-popup {
  position: fixed;
  left: 0; right: 0; bottom: 0;
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 32rpx;
  min-height: 400rpx;
  z-index: 10000;

  .cart-title { font-size: 32rpx; font-weight: bold; margin-bottom: 24rpx; }

  .cart-empty { text-align: center; color: #999; font-size: 28rpx; margin: 40rpx 0; }

  .cart-item { display: flex; align-items: center; margin-bottom: 24rpx; }

  .cart-item-img { width: 80rpx; height: 80rpx; border-radius: 8rpx; margin-right: 16rpx; }

  .cart-item-name { font-size: 28rpx; color: #333; flex: 1; }

  .cart-item-controls { display: flex; align-items: center; }

  .cart-footer { margin-top: 32rpx; display: flex; justify-content: flex-end; }

  .checkout-btn { background: #ffcc00; color: #fff; font-size: 32rpx; border-radius: 40rpx; padding: 16rpx 60rpx; border: none; opacity: 0.6; }
}

.cart-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 16rpx 32rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1);

  .cart-bar-icon {
    width: 60rpx;
    height: 60rpx;
    margin-right: 16rpx;
  }

  .cart-bar-amount {
    flex: 1;
    font-size: 28rpx;
    color: #333;

    .cart-bar-price {
      color: #ff0000;
      font-weight: bold;
    }
  }

  .cart-bar-pay-btn {
    background-color: #ffcc00;
    color: #333;
    font-size: 28rpx;
    padding: 10rpx 20rpx;
    border-radius: 40rpx;
    border: none;
    opacity: 0.8;

    &:disabled {
      background-color: #ddd;
      color: #999;
    }
  }
}

.notice-bar {
  background-color: #fffbe6;
  padding: 16rpx;
  border-radius: 8rpx;
  margin-bottom: 24rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);

  .notice-content {
    font-size: 28rpx;
    color: #333;
    flex: 1;
  }
}
</style>
